<?php

namespace app\modules\weixin\controllers;

use app\common\services\ShortMessageServices;
use app\common\services\StaticServices;
use app\models\Member;
use app\models\Recommend;
use app\models\User;
use app\modules\weixin\controllers\common\BaseController;
use Yii;
use yii\base\Exception;
use yii\helpers\Url;
use yii\web\Response;

class CommonController extends BaseController {
  public function actionLogin()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $phone = trim(Yii::$app->request->post('user_phone', ''));
      $user_pwd = trim(Yii::$app->request->post('user_pwd', ''));
      $member_info = Member::find()->where(['member_phone' => $phone, 'self_status' => 1])->one();
      if (mb_strlen($phone, 'utf-8') != 11 && !preg_match("/^1[34578]{1}\d{9}$/", $phone)) {
        throw new Exception('请填写正确的电话号码');
      }
      if (!$member_info) {
        throw new Exception("-1");
      }

      if (!Member::checkPwd($user_pwd, $phone)) {
        throw new Exception('密码或者用户名有误');
      }

      return ['code' => 200, 'member_info' => $member_info];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }


  public function actionModifyPwd()
  {
    Yii::$app->response->format = Response::FORMAT_JSON;
    try {
      $member_id = intval(Yii::$app->request->post('member_id'));
      $new_pwd = trim(Yii::$app->request->post('new_pwd'));
      $confirm_pwd = trim(Yii::$app->request->post('confirm_pwd'));
      if (mb_strlen($new_pwd, 'utf-8') < 6 || mb_strlen($confirm_pwd, 'utf-8') < 6 || $new_pwd != $confirm_pwd) {
        throw new Exception('填写密码有误');
      }
      $member_info = Member::find()->where(['id' => $member_id, 'self_status' => 1])->one();
      $member_info->member_pwd = md5($new_pwd);
      $member_info->save(0);
      return ['code' => 200, 'msg' => '更新成功'];
    } catch (Exception $e) {
      return ['code' => -200, 'msg' => $e->getMessage()];
    }
  }

  public function actionTest()
  {
    $recommend_info = Recommend::find()->where(['recommend_type' => 9])->asArray()->all();
    foreach ($recommend_info as $item) {
      if (time() - $item['update_time'] > 60 * 60) {
        $recommend = Recommend::find()->where(['id' => $item['id']])->one();
        $recommend->recommend_type = 7;
        $recommend->update_time = time();
        $recommend->save(0);
      }
    }
    echo 123;
  }
}